import {Component, OnInit, Input, Optional, ElementRef, ViewChild, HostListener, EventEmitter} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
  FormControl,
} from '@angular/forms';
import {NzMessageService, NzDrawerRef} from 'ng-zorro-antd';
import {I18NService} from '../../../core/i18n/i18n.service';

import {BaseComponent} from '../../../shared/base/base.component';
import {PaperService} from "../service/paper.service";
import {AutoPaperQuestionNum, ExportFormValue, QuestionNumData} from "../model/paper";
import {HeaderParam, HttpServer} from "../../../core/net/http-server";
import {HttpClient, HttpResponse} from "@angular/common/http";
import { saveAs } from 'file-saver';
import {Knowledge} from "../../knowledge/model/knowledge";

@Component({
  templateUrl: './paper-autoAdd.html'
})
export class PaperAutoAddComponent extends BaseComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    @Optional() private drawerRef: NzDrawerRef<any>,
    private i18nService: I18NService,
    private paperService: PaperService,
    private http: HttpClient
  ) {
    super();
    this.validateForm = this.fb.group({
      paperName: [null, [Validators.required]],
      describe: null,
      knowledgeListValue:null,
      choiceNum:0,
      choiceScore:1
    });
  }
  choiceNum:0;
  choiceScore:1;
  knowledgeList: Knowledge[];
  knowledgeListValue:string[];
  autoPaperQuestionNumList:AutoPaperQuestionNum[];
  /**
   * 弹出对话框
   */
  isVisible = false;
  showModal(): void {
    this.isVisible = true;
  }
  auto:AutoPaperQuestionNum=new AutoPaperQuestionNum();
  numOption: Array<{ num: string}> = [];
  scoreOption: Array<{ score: string}> = [];
  extendOption: Array<{ extend: boolean}> = [];
  isChoiceByTypeOption:Array<{ isChoice: boolean}> = [];
  difficultyOption:Array<{ difficulty: string}> = [];
  numPackage = [];
  scorePackage=[];
  hasKnowledge=false;
  handleOk(): void {
    this.getKnowledgeList();
    this.autoPaperQuestionNumList=[];
    this.numOption.forEach(res=>this.validateForm.removeControl(res.num));
    this.scoreOption.forEach(res=>this.validateForm.removeControl(res.score));
    this.difficultyOption.forEach(res=>this.validateForm.removeControl(res.difficulty));
    this.numOption=[];
    this.scoreOption=[];
    this.difficultyOption=[];
    this.extendOption=[];
    this.isChoiceByTypeOption=[];
    for(let i=0;i<this.numPackage.length;i++){
      this.numPackage[i].forEach(res=>this.validateForm.removeControl(res.typeNum));
    }
    this.numPackage=[];
    for(let i=0;i<this.scorePackage.length;i++){
      this.scorePackage[i].forEach(res=>this.validateForm.removeControl(res.typeScore));
    }
    this.scorePackage=[];
    if (this.knowledgeListValue!=undefined){
      /**
       * 怎加表单变量
       */
      for (let i = 0; i < this.knowledgeListValue.length; i++) {
        this.numOption .push({ num: 'num' + i});
        this.scoreOption .push({ score: 'score' + i});
        this.difficultyOption .push({ difficulty: 'difficulty' + i});
        this.extendOption.push({extend:false});
        this.isChoiceByTypeOption.push({isChoice:false});
        this.validateForm.addControl(
          this.numOption[i].num,
          new FormControl(0, Validators.required)
        );
        this.validateForm.addControl(
          this.scoreOption[i].score,
          new FormControl(1, Validators.required)
        );
        this.validateForm.addControl(
          this.difficultyOption[i].difficulty,
          new FormControl('简单', Validators.required)
        );
      }
      this.knowledgeListValue.forEach(value=>{
        this.knowledgeList.forEach(knowledge=>{
          if(knowledge.knowledgeName==value){
            const typeNumOption:Array<{ typeNum: string}> = [];
            const typeScoreOption: Array<{ typeScore: string}> = [];
            if(knowledge.questionTypeNumList!=undefined&&knowledge.questionTypeNumList.length>0){
              for(let j=0;j<knowledge.questionTypeNumList.length;j++){
                typeNumOption.push({typeNum:knowledge.knowledgeName+'num'+j});
                typeScoreOption.push({typeScore:knowledge.knowledgeName+'score'+j});
                this.validateForm.addControl(
                  typeNumOption[j].typeNum,
                  new FormControl(0, Validators.required)
                );
                this.validateForm.addControl(
                  typeScoreOption[j].typeScore,
                  new FormControl(1, Validators.required)
                );
              }
            }
            this.numPackage.push(typeNumOption);
            this.scorePackage.push(typeScoreOption);
            let params = {
              questionAllNum:knowledge.questionAllNum,
              questionChoiceNum:0,
              allScore:0,
              choiceScore:1,
              knowledgeName:knowledge.knowledgeName,
              difficulty:null,
              questionTypeNumList:knowledge.questionTypeNumList
            };
            this.autoPaperQuestionNumList.push(params);
          }
        });
      });

    }
    this.hasKnowledge=true;
    this.isVisible = false;
  }
  handleCancel(): void {
    this.isVisible = false;
  }
  changeChoiceNum(i:number,e):void{
    this.autoPaperQuestionNumList[i].questionChoiceNum=e;
    this.autoPaperQuestionNumList[i].allScore=this.autoPaperQuestionNumList[i].choiceScore*e;
    console.log(this.autoPaperQuestionNumList[i]);
  }
  changeAllScore(i:number,e):void{
    this.autoPaperQuestionNumList[i].choiceScore=e;
    this.autoPaperQuestionNumList[i].allScore=this.autoPaperQuestionNumList[i].questionChoiceNum*e;
    console.log(this.autoPaperQuestionNumList);
  }
  extendChangeShow(i:number):void{
    this.extendOption[i].extend=!this.extendOption[i].extend;
  }

  /**
   * 根据题型修改题目数量
   * @param i
   * @param j
   * @param e
   */
  changeTypeNumOption(i:number,j:number,e){
    this.autoPaperQuestionNumList[i].questionTypeNumList[j].typeQuestionChoiceNum=e;
    let questionNumTotal=0;
    let scoreTotal=0;
    for(let x=0;x<this.autoPaperQuestionNumList[i].questionTypeNumList.length;x++){
      if(this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeScore===undefined){
        this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeScore=1;
      }
      if(this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum===undefined){
        this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum=0;
      }
      questionNumTotal=questionNumTotal+this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum;
      scoreTotal=scoreTotal+this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum*this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeScore
    }
    this.autoPaperQuestionNumList[i].questionChoiceNum=questionNumTotal;
    if(questionNumTotal>0){
      this.isChoiceByTypeOption[i].isChoice=true;
    }else{
      this.isChoiceByTypeOption[i].isChoice=false;
    }
    this.autoPaperQuestionNumList[i].allScore=scoreTotal;
  }
  /**
   * 根据题型修改题目分数
   * @param i
   * @param j
   * @param e
   */
  changeTypeScoreOption(i:number,j:number,e){
    this.autoPaperQuestionNumList[i].questionTypeNumList[j].typeScore=e;
    let questionNumTotal=0;
    let scoreTotal=0;
    for(let x=0;x<this.autoPaperQuestionNumList[i].questionTypeNumList.length;x++){
      if(this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeScore===undefined){
        this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeScore=1;
      }
      if(this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum===undefined){
        this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum=0;
      }
      questionNumTotal=questionNumTotal+this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum;
      scoreTotal=scoreTotal+this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeQuestionChoiceNum*this.autoPaperQuestionNumList[i].questionTypeNumList[x].typeScore;
    }
    this.autoPaperQuestionNumList[i].questionChoiceNum=questionNumTotal;
    if(questionNumTotal>0){
      this.isChoiceByTypeOption[i].isChoice=true;
    }else{
      this.isChoiceByTypeOption[i].isChoice=false;
    }

    this.autoPaperQuestionNumList[i].allScore=scoreTotal;
  }

  difficultyChange(i,question:AutoPaperQuestionNum,e){
    this.numPackage[i].forEach(res=>this.validateForm.removeControl(res.typeNum));
    this.scorePackage[i].forEach(res=>this.validateForm.removeControl(res.typeScore));
    this.paperService.getAutoPaperQuestionNumByDifficulty(e,question.knowledgeName).subscribe(res=>{
      this.autoPaperQuestionNumList[i]=res;
      const typeNumOption:Array<{ typeNum: string}> = [];
      const typeScoreOption: Array<{ typeScore: string}> = [];
      if(res.questionTypeNumList!=undefined&&res.questionTypeNumList.length>0) {
        for (let j = 0; j < res.questionTypeNumList.length; j++) {
          typeNumOption.push({typeNum: res.knowledgeName + 'num' + j});
          typeScoreOption.push({typeScore: res.knowledgeName + 'score' + j});
          this.validateForm.addControl(
            typeNumOption[j].typeNum,
            new FormControl(0, Validators.required)
          );
          this.validateForm.addControl(
            typeScoreOption[j].typeScore,
            new FormControl(1, Validators.required)
          );
        }
      }
      this.numPackage[i]=typeNumOption;
      this.scorePackage[i]=typeScoreOption;
    });

  }

  header = true;
  allChecked = false;
  indeterminate = false;
  displayData: any[] = [];
  refreshStatus(): void {
    const validData = this.displayData.filter(value => !value.disabled);
    const allChecked = validData.length > 0 && validData.every(value => value.checked === true);
    const allUnChecked = validData.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }
  checkAll(value: boolean): void {
    this.displayData.forEach(data => {
      if (!data.disabled) {
        data.checked = value;
      }
    });
    this.refreshStatus();
  }

  validateForm: FormGroup;
  isCheck = true;
  tabIndex = 0;
  describe:string;
  paperName:string;
  questionNum:QuestionNumData=new QuestionNumData();


  ngOnInit(): void {
    this.getKnowledgeList();
  }

  nextTab(): void {
    this.tabIndex = this.tabIndex + 1;
  }

  lastTab(): void {
    this.tabIndex = this.tabIndex - 1;
  }

  getKnowledgeList():void{
    this.paperService.getKnowledgeList().subscribe(res=>{
      this.knowledgeList=res;
    });
  }

  getQuestionNumber(): void {
    this.paperService.getQuestionNumber()
      .subscribe(res => {
        this.questionNum=res;
      });
  }

  error: EventEmitter<any> = new EventEmitter<any>();
  exportFormValue:ExportFormValue=new ExportFormValue() ;
  submitForm(): void{
    this.exportFormValue.autoPaperQuestionNumList=this.autoPaperQuestionNumList;
    this.exportFormValue.paperName=this.validateForm.value.paperName;
    this.exportFormValue.paperDescribe=this.validateForm.value.paperDescribe;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    this.http.post( '/post/web/download/paperModule/PaperService/autoExportPaper', this.exportFormValue,{responseType:'blob',observe:'response'})
      .subscribe(res => {
        if (res.status !== 200 || res.body.size <= 0) {
          this.error.emit(res);
          return;
        }
        debugger
        const name=res.headers.get('Content-disposition');
        const disposition: any = this.getDisposition(name);
        const fileName =
          disposition[`filename*`] ||
          disposition[`filename`] ||
          res.headers.get('filename') ||
          res.headers.get('x-filename');
        saveAs(res.body, decodeURI(fileName));
      }, err => {
      });
  }
  submitFormOld(): void{
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    this.http.post( '/post/web/download/paperModule/PaperService/exportPaper', this.validateForm.value,{responseType:'blob',observe:'response'})
      .subscribe(res => {
        if (res.status !== 200 || res.body.size <= 0) {
          this.error.emit(res);
          return;
        }
        debugger
        const name=res.headers.get('Content-disposition');
        const disposition: any = this.getDisposition(name);
        const fileName =
          disposition[`filename*`] ||
          disposition[`filename`] ||
          res.headers.get('filename') ||
          res.headers.get('x-filename');
        saveAs(res.body, decodeURI(fileName));
      }, err => {
      });
  }


  private getDisposition(data: string) {
    const arr: any = (data || '')
      .split(';')
      .filter(i => i.includes('='))
      .map(v => {
        const strArr = v.split('=');
        const utfId = `UTF-8''`;
        let value = strArr[1];
        if (value.startsWith(utfId)) {
          value = value.substr(utfId.length);
        }
        return { [strArr[0].trim()]: value };
      });
    return arr.reduce((o, item: any) => item, {});
  }





}


